﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace PhotoManager
{
    /// <summary>
    /// Contains information about a photo.
    /// </summary>
    public class PhotoInfo
    {
        private readonly ContentHash m_contentHash;
        private readonly ColorDistribution m_colorDistribution;

        /// <summary>
        /// Gets the SHA256 hash value of the file's content, or null if the
        /// file's content hash is never computed.
        /// </summary>
        public ContentHash ContentHash
        {
            get { return m_contentHash; }
        }

        /// <summary>
        /// Gets or sets the color distribution of the photo, or null if the
        /// file is not an image.
        /// </summary>
        public ColorDistribution ColorDistribution
        {
            get { return m_colorDistribution; }
        }

        public PhotoInfo(ContentHash contentHash, ColorDistribution colorDistribution)
        {
            m_contentHash = contentHash;
            m_colorDistribution = colorDistribution;
        }

        public PhotoInfo(string fileName)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            try
            {
                m_contentHash = ContentHash.Compute(fileName);
            }
            catch (Exception) { }

            try
            {
                m_colorDistribution = ColorDistribution.Compute(fileName, 256);
            }
            catch (Exception) { }
        }

        /// <summary>
        /// Returns the string representation of this object.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Format("{0}:{1}",
                m_contentHash == null ? "" : m_contentHash.ToString(),
                m_colorDistribution == null ? "" : m_colorDistribution.ToString()
                );
        }

        public static PhotoInfo Parse(string s)
        {
            if (s == null)
                throw new ArgumentNullException("s");

            string[] fields = s.Split(':');
            if (fields.Length != 2)
                throw new ArgumentException("Input string must contain 2 colon-separated fields.");

            PhotoInfo photoInfo = new PhotoInfo(
                fields[0] == "" ? null : ContentHash.Parse(fields[0]),
                fields[1] == "" ? null : ColorDistribution.Parse(fields[1])
                );
            return photoInfo;
        }
    }
}
